﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using System.Collections.Generic;
using Utils;
using DataBaseConnect.App;
using System;
using Business;
using Domain;
using System.Net;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CoreMVC.Jurisdiction.Manage.Controllers
{
    public class LoginController : Controller
    {
        public IUserAppService _userAppService;
        public IRoleAppService _roleAppService;
        public static string _ReidsConne { get { return AppConfigurtaionServices.Configuration["Appsettings:RedisConnection"]; } }
        RedisHelper redisHelper = new RedisHelper(_ReidsConne);
        public LoginController(IUserAppService userAppService, IRoleAppService roleAppService)
        {
            _userAppService = userAppService;
            _roleAppService = roleAppService;
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Login()
        {
            string host = HttpContext.Request.Host.Value;
            string url = HttpContext.Request.QueryString.Value.Trim('?');
            var returnUrl = WebUtility.UrlDecode(url).Replace("ReturnUrl=", "");
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                if (url.Contains("http"))
                {
                    return Redirect(string.Concat(returnUrl));
                }
                else
                {
                    return RedirectToAction("Main", "Home");
                }

            }
            return View();
        }

        /// <summary>
        ///  登录验证
        /// </summary>  
        /// <param name="Name">登录姓名</param>
        /// <param name="Password">登录密码</param>
        /// <param name="ReturnUrl">登录前访问地址</param>
        /// <returns>陈杰 by 2017-09-15</returns>
        // GET: /<controller>/
        public async Task<IActionResult> LoginAsync(string Name, string Password, string ReturnUrl)
        {
            OperateStatus operateStatus = new OperateStatus();
            if (ModelState.IsValid)
            {
                try
                {
                    //登陆授权
                    var claims = new List<Claim>();
                    var user = _userAppService.GetUser(Name, Password);
                    if (user != null)
                    {
                        var roleId = _roleAppService.GetUserRole(user.UserId);
                        // 保存要记录的值(cookie)
                        claims.Add(new Claim(ClaimTypes.Name, Name));  // 用户名
                        var indentity = new ClaimsIdentity(claims, "cookie");
                        indentity.AddClaim(new Claim("Password", Password)); // 密码
                        indentity.AddClaim(new Claim(ClaimTypes.Sid, user.UserId.ToString())); // 用户id
                        indentity.AddClaim(new Claim("RoleUserId", roleId == null ? 0.ToString() : roleId.RoleId.ToString())); // 登录用户角色id
                        var principal = new ClaimsPrincipal(indentity);
                        await HttpContext.SignInAsync(
                            CookieAuthenticationDefaults.AuthenticationScheme,
                            principal);

                        //验证是否授权成功
                        if (principal.Identity.IsAuthenticated)
                        {
                            //生成token并保存到redis
                            var NameStr = string.Format("\"{0}\"", Name);
                            string tokenName = DEncryptStatus.Base64Encrypt(Name + user.UserId);
                            string tokenValue = DEncryptStatus.Base64Encrypt("{" + "UserName" + ":"+NameStr+"," + "UserId" + ":" + user.UserId + "}");
                            bool status = redisHelper.SetEntity(tokenName, tokenValue, new TimeSpan(24, 0, 0));
                            //token保存到客户端（和redis进行比较）
                            var _httpContext = HttpContext;
                            CookiesHelper cookiesHelper = new CookiesHelper(_httpContext);
                            cookiesHelper.SaveCookiesValue("TokenName", tokenValue, 1440);
                            operateStatus.Message = "登录成功";
                            operateStatus.ResultSign = ResultSign.Successful;
                            //  return RedirectToAction("Index");
                        }
                    }
                }
                catch (Exception ex)
                {
                    operateStatus.Message = "登录失败";
                    operateStatus.ResultSign = ResultSign.Error;
                    throw;
                }
            }
            else
            {
                operateStatus.Message = "登录失败";
                operateStatus.ResultSign = ResultSign.Error;
            }
            return Json(operateStatus);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout(string ReturnUrl)
        {
            // 用户用户信息
            //var userId = User.FindFirst(ClaimTypes.Sid).Value;
            //var userName = User.Identity.Name;

            //获取用户名方法2  
            //string username2 = User.FindFirst(ClaimTypes.Name).Value;
            //获取名字叫password的值  
            // string password = User.FindFirst("Password").Value;


            OperateStatus operateStatus = new OperateStatus();
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                try
                {
                    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    var _httpContext = HttpContext;
                    CookiesHelper cookiesHelper = new CookiesHelper(_httpContext);
                    cookiesHelper.DeleteCookies("TokenName");
                    operateStatus.Message = "退出成功";
                    operateStatus.ResultSign = ResultSign.Successful;
                }
                catch (System.Exception e)
                {
                    operateStatus.Message = "退出失败" + e.Message;
                    operateStatus.ResultSign = ResultSign.Error;
                }
            }
            return Json(operateStatus);
        }
    }
}
